﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using FastDFS.Client;

namespace Client
{
    public partial class Form1 : Form
    {
        private string _filename = Application.StartupPath + "/filelist.xml";
        public Form1()
        {
            InitializeComponent();
        }
        private void OperationXML(string msg,string type="add") {
            type = type.ToLower();
            XmlDocument xml = new XmlDocument();
            if (File.Exists(this._filename))
            {
                xml.Load(this._filename);
                if (type == "dec")
                {
                    XmlNode root = xml.SelectSingleNode("list");
                    XmlNodeList list= root.SelectNodes("file");
                    foreach (XmlNode n in list)
                    {
                        if (n.InnerText.Contains(msg)) {
                            root.RemoveChild(n);
                            break;
                        }
                    }
                }
            }
            else
            {
                XmlDeclaration xmld = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
                xml.AppendChild(xmld);
                XmlElement xmlelem = xml.CreateElement("", "list", "");
                xml.AppendChild(xmlelem);
            }
            if (type == "add")
            {
                XmlNode root = xml.SelectSingleNode("list");

                XmlElement xmle = xml.CreateElement("file");
                xmle.InnerText = msg;
                root.AppendChild(xmle);
            }
            xml.Save(this._filename);
        }
        private void ConnectionDFS()
        {
            List<IPEndPoint> trackerIPs = new List<IPEndPoint>();
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.42.151"), 22122);
            trackerIPs.Add(endPoint);
            ConnectionManager.Initialize(trackerIPs);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = "图片(*.jpg)|*.jpg";
            this.openFileDialog1.FileName = string.Empty;
            this.openFileDialog1.Multiselect = false;
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {

                string filename = this.openFileDialog1.FileName;

                ConnectionDFS();
                StorageNode node = FastDFSClient.GetStorageNode();

                byte[] content = null;
                
                FileStream streamUpload = new FileStream(filename, FileMode.Open);
                using (BinaryReader reader = new BinaryReader(streamUpload))
                {
                    content = reader.ReadBytes((int)streamUpload.Length);
                }

                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                string fdspath = FastDFSClient.UploadFile(node, content, Path.GetExtension(filename).TrimStart('.'));
                fdspath = node.GroupName + "/" + fdspath;
                OperationXML(fdspath);
                this.listBox1.Items.Add(fdspath);
                MessageBox.Show("上传成功");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(this._filename))
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(this._filename);

                XmlNodeList xmls = xml.SelectSingleNode("list").SelectNodes("file");
                foreach (XmlNode n in xmls)
                {
                    this.listBox1.Items.Add(n.InnerText);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedIndex != -1)
            {
                this.saveFileDialog1.Filter = "图片(*.jpg)|*.jpg";
                this.saveFileDialog1.InitialDirectory = Application.StartupPath;
                if (DialogResult.OK == this.saveFileDialog1.ShowDialog())
                {
                    string filepath = this.saveFileDialog1.FileName;
                    string fileName = this.listBox1.SelectedItem.ToString();
                    string group;
                    if (fileName.StartsWith("group")) { 
                        group=fileName.Split('/')[0];
                        fileName=fileName.Substring(group.Length+1);
                    }else{
                        group="group1";
                    }

                    //ConnectionDFS();
                    //StorageNode storage= FastDFSClient.GetStorageNode(group);
                    //byte[] buffer = FastDFSClient.DownloadFile(storage, fileName,0L,0L);

                    if (File.Exists(filepath))
                        File.Delete(filepath);

                    string url = string.Format("http://192.168.42.151/{0}", fileName);
                    System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                    System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
                    Image myImage = Image.FromStream(res.GetResponseStream());
                    myImage.Save(filepath);//保存
                    res.Close();
                    myImage.Dispose();

                    MessageBox.Show("下载成功！");
                }
            }
            else {
                MessageBox.Show("请在文件列表选择需要下载的文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int index=this.listBox1.SelectedIndex ;
            if (index != -1)
            {
                string fileName = this.listBox1.SelectedItem.ToString();
                string group;
                if (fileName.StartsWith("group"))
                {
                    group = fileName.Split('/')[0];
                    fileName = fileName.Substring(group.Length + 1);
                }
                else
                {
                    group = "group1";
                }
                ConnectionDFS();
                FastDFSClient.RemoveFile(group, fileName);
                this.listBox1.Items.RemoveAt(index);
                OperationXML(fileName, "dec");
                MessageBox.Show("删除成功！");
            }
            else
            {
                MessageBox.Show("请在文件列表选择需要删除的文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}
